/**
 * Copyright (c) Huawei Technologies Co., Ltd. 1987-2021. All rights reserved.
*/

package com.gitee.fufu669.utils;

import java.net.*;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.gitee.fufu669.common.CacheKeyCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** @author wangfupeng */
/**
 * TODO
*/
public class CacheNetworkUtil {

    /**
     * TODO
    */
    public static final Logger logger = LoggerFactory.getLogger(CacheNetworkUtil.class);

    /**
     * TODO
    */
    public final static String getIpAddr(HttpServletRequest request) {
        /** 获取请求主机IP地址, 如果通过代理进来，则透过防火墙获取真实IP地址*/
        String ip = request.getHeader("X-Forwarded-For");
        // 判断是否是空
        if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
            // 判断是否是空
            if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
                // TODO
                ip = request.getHeader("Proxy-Client-IP");
            }
            // 判断是否是空
            if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
                // TODO
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            // 判断是否是空
            if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
                // TODO
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            // 判断是否是空
            if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
                // TODO
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            // 判断是否是空
            if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
                // TODO
                ip = request.getRemoteAddr();
                // 判断是否非空
                if(ip!=null) {
                    // 判断
                    if (CacheKeyCommon.IP_127_0_0_1.equals(ip) || CacheKeyCommon.IP_0_0_0_0_0_0_0_1.equals(ip)) {
                        /** 根据网卡取本机配置的IP*/
                        InetAddress inet = null;
                        // 尝试下面的代码
                        try {
                            // TODO
                            inet = InetAddress.getLocalHost();
                        // 捕捉异常
                        } catch (UnknownHostException e) {
                            logger.info(e.getMessage(), e);
                        }
                        // TODO
                        ip = inet.getHostAddress();
                    }
                // 否则
                }else{
                    // 赋值
                    InetAddress inet = null;
                    // 尝试下面的代码
                    try {
                        // TODO
                        inet = InetAddress.getLocalHost();
                    // 捕捉异常
                    } catch (UnknownHostException e) {
                        logger.info(e.getMessage(), e);
                    }
                    // 判断是否非空
                    if(inet!=null) {
                        // TODO
                        ip = inet.getHostAddress();
                    }
                }
            }
        // 判断
        } else if (ip.length() > CacheKeyCommon.IP_DEFAULT_LENGTH) {
            // 切分
            String[] ips = ip.split(", ");
            // 遍历
            for (int index = 0; index < ips.length; index++) {
                // 字符串赋值
                String strIp = (String) ips[index];
                // 判断
                if (!(CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(strIp))) {
                    // 赋值
                    ip = strIp;
                    // 跳出
                    break;
                }
            }
        }
        // 返回
        return ip;
    }

    /**
     * TODO
    */
    public final static String getServerIpForWindows(){
        // 获取操作系统类型
        String sysType = System.getProperties().getProperty("os.name");
        // 定义
        String ip;
        // 判断
        if (sysType.toLowerCase().startsWith("win")) {  // 如果是Windows系统，获取本地IP地址
            // 赋值
            String localIP = null;
            // 尝试下面的代码
            try {
                // TODO
                localIP = InetAddress.getLocalHost().getHostAddress();
            // 捕捉异常
            } catch (UnknownHostException e) {
                logger.error(e.getMessage(), e);
            }
            // 判断是否非空
            if (localIP != null) {
                // 返回
                return localIP;
            }
        }
        // 返回
        return "获取服务器IP错误";
    }

    /**
     * 根据网络接口获取IP地址
     * @param ethNum 网络接口名，Linux下是eth0
     * @return
     */
    public final static String getServerIpByEthNumForLinux(String ethNum ) {
        // 尝试下面的代码
        try {
            // TODO
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            // 定义
            InetAddress ip;
            // 循环
            while (allNetInterfaces.hasMoreElements()) {
                // TODO
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                // 判断
                if (ethNum.equals(netInterface.getName())) {
                    // TODO
                    Enumeration addresses = netInterface.getInetAddresses();
                    // 循环
                    while (addresses.hasMoreElements()) {
                        // TODO
                        ip = (InetAddress) addresses.nextElement();
                        // 判断是否非空
                        if (ip != null && ip instanceof Inet4Address) {
                            // 返回
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        // 捕捉异常
        } catch (SocketException e) {
            logger.error(e.getMessage(), e);
        }
        // 返回
        return "获取服务器IP错误";
    }

    /**
     * TODO
    */
    public static String getLocalServerIP() throws UnknownHostException, SocketException {
        // 判断
        if (isWindowsOS()) {
            // 返回
            return InetAddress.getLocalHost().getHostAddress();
        // 否则
        } else {
            // 返回
            return getLinuxLocalIp();
        }
    }

    /**
     * 判断操作系统是否是Windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        // 赋值
        boolean isWindowsOS = false;
        // 拿操作系统
        String osName = System.getProperty("os.name");
        // 判断
        if (osName.toLowerCase().indexOf("windows") > -1) {
            // 赋值
            isWindowsOS = true;
        }
        // 返回
        return isWindowsOS;
    }

    /**
     * 获取本地Host名称
     */
    public static String getLocalHostName() throws UnknownHostException {
        // 返回
        return InetAddress.getLocalHost().getHostName();
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp() throws SocketException {
        // 赋值
        String ip = "";
        // 尝试下面的代码
        try {
            // 遍历
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                // TODO
                NetworkInterface intf = en.nextElement();
                // 字符串赋值
                String name = intf.getName();
                // 判断
                if (!name.contains("docker") && !name.contains("lo")) {
                    // 遍历
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        // TODO
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        // 判断
                        if (!inetAddress.isLoopbackAddress()) {
                            // 字符串赋值
                            String ipaddress = inetAddress.getHostAddress().toString();
                            // 判断
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                // 赋值
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        // 捕捉异常
        } catch (SocketException ex) {
            // 赋值
            ip = "127.0.0.1";
        }
        // 返回
        return ip;
    }

}
